package com.estore.network;

import com.estore.Product;
import com.estore.ProductService;
import com.estore.ProductSorters;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.*;

public class EStoreClient {
ProductService productService=new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);
    private final String serverHost;
    private final int serverPost;
    public EStoreClient(String serverHost,int serverPost){
        this.serverHost=serverHost;
        this.serverPost=serverPost;
    }

    public void start() throws Exception{
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费掉换行符
            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    showSortedProducts();
                    break;
                case 5:
                    productService.saveData();
                    System.out.println("数据已保存。感谢使用，再见！");
                    return;
                case 99:
                    productService.backupData();
                    break;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
    }

    private void showMenu() {
        System.out.println("\n ----欢迎来到商城---- ");
        System.out.println("1. 浏览所有商品");
        getPrintln();
        System.out.println("3. 查看购物车");
        System.out.println("4，自定义排序浏览商品");
        System.out.println("5. 退出");
        System.out.println("99. 备份数据");
        System.out.print("请输入您的选择: ");
    }

    private static void getPrintln() {
        System.out.println("2. 添加商品到购物车");
    }

    private void browseProducts(Comparator<Product> productComparator) throws Exception{
        Socket socket=new Socket(serverHost,serverPost);
        try{
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();
            List<Product> products=(List<Product>) ois.readObject();
            System.out.println("\n--- 商品列表 ---");
            if (products.isEmpty()) {
                System.out.println("商店里还没有商品。");
            } else {
                products.sort(productComparator);
                products.forEach(System.out::println);
            }
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            try{

                    socket.close();

            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
    private void browseProducts() throws Exception{
        Socket socket=new Socket(serverHost,serverPost);
        try{
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
            oos.writeObject("GET_ALL_PRODUCTS");
            oos.flush();
            List<Product> products=(List<Product>) ois.readObject();
            System.out.println("\n--- 商品列表 ---");
            if (products.isEmpty()) {
                System.out.println("商店里还没有商品。");
            } else {
                products.forEach(System.out::println);
            }
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            try{

                socket.close();

            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    private void addToCart() throws Exception{
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Socket socket=new Socket(serverHost,serverPost);
        try{
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
            oos.writeObject(productId);
            oos.flush();
            Product product=(Product) ois.readObject();
            if (product == null) {
                System.out.println("错误：找不到该商品！");
                return;
            }
            if (product.getStock() <= 0) {
                System.out.println("抱歉，该商品已售罄。");
                return;
            }

            System.out.print("请输入购买数量: ");
            int quantity = scanner.nextInt();
            scanner.nextLine(); // 消费换行符

            if (quantity <= 0) {
                System.out.println("错误：购买数量必须为正数！");
                return;
            }
            if (quantity > product.getStock()) {
                System.out.println("错误：库存不足！当前库存为 " + product.getStock());
                return;
            }

            // 将商品加入购物车，如果已存在则累加数量
            shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
            System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            try{

                    socket.close();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void viewCart() throws Exception{
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }
        Socket socket=new Socket(serverHost,serverPost);
        double total = 0.0;
        try{
            for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
                String productId = entry.getKey();
                Integer quantity = entry.getValue();
                ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
                oos.writeObject(productId);
                oos.flush();
                Product product=(Product) ois.readObject();
                if (product != null) {
                    double subtotal = product.getPrice() * quantity;
                    System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n", product.getName(), product.getPrice(), quantity, subtotal);
                    total += subtotal;
                }
            }
            System.out.println("------------------------------------");
            System.out.printf("总计: ¥%.2f\n", total);
            }catch (Exception e){
                e.getStackTrace();
            }finally {
                try{
                        socket.close();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

    }
    private void showSortedProducts() throws  Exception{
        subMenu();
        int choose = scanner.nextInt();
        scanner.nextLine(); // 消费掉换行符
        switch (choose) {
            case 1:
                browseProducts(ProductSorters.BY_PRICE_ASC);
                break;
            case 2:
                browseProducts(ProductSorters.BY_PRICE_DESC);
                break;
            case 3:
                browseProducts(ProductSorters.BY_STOCK_DESC);
                break;
            case 4:
                System.out.println("感谢使用，再见！");
                break;
            default:
                System.out.println("无效的选项，请重新输入！");
        }
    }
    private void subMenu(){
        System.out.println("\n ----自定义排序浏览商品---- ");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3，按库存量从高到低");
        System.out.println("4. 退出");
        System.out.print("请输入您的选择: ");
    }

    public static void main(String[] args) throws  Exception{
        EStoreClient client=new EStoreClient("localhost",8888);
        client.start();
    }
}